//
//  MallListViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/9/7.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "MallListViewController.h"
#import "MallsCollectionViewCell.h"
#import "MallDetailViewController.h"
#import "Goods.h"
#import "SearchViewController.h"
//#import "MallClassificationViewController.h"
#import "MallHomeViewController.h"

@interface MallListViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource>

@property (nonatomic, assign) NSInteger page; // 网络请求页数
@property (nonatomic, strong) NSMutableArray *infoArr;
@property (nonatomic, strong) NSArray *pickerArr;
@property (nonatomic, strong) NSString *pickerStr;

@property (nonatomic, assign) BOOL isTop; // 当选择器点击确定时，需要回到top

@end

@implementation MallListViewController {
    
    UICollectionView *_collectionView;
    MallsCollectionViewCell *_item;
    
    UIView                  *_pickerBgView;
    UIPickerView            *_picker;
    UIView                  *_pickerToolbgView;
    
    CGFloat         _collectionW;
    CGFloat         _collectionH;
    
    UIView          *_screeningBgView;
    UIButton        *_priceSortedBtn;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.isTop = 0;
    self.page = 1;
    self.pickerArr = @[@"价格↑", @"价格↓"];
    self.pickerStr = @"";
    
    [self GETMallsGoods];
    
    [self createUI];
    
    [self refreshData];
    
}


#pragma mark ==========构建UI==========
- (void)createUI {
    
    self.navigationItem.title = self.titleName;
    
    self.view.backgroundColor = UISeparatedColorRGB;
    
    // 左上角返回
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"return"] style:UIBarButtonItemStylePlain target:self action:@selector(returnAction:)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@""] style:UIBarButtonItemStylePlain target:self action:@selector(navRithAction:)];
    [self.navigationItem.rightBarButtonItem setImage:[[UIImage imageNamed:@"zhibo_search"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    
    _screeningBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    [self.view addSubview:_screeningBgView];
    _screeningBgView.backgroundColor = kWhiteColor;
    
    _priceSortedBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_screeningBgView addSubview:_priceSortedBtn];
    [_priceSortedBtn setTitle:@"综合" forState:UIControlStateNormal];
    [_priceSortedBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    [_priceSortedBtn setTitleColor:kRedColor forState:UIControlStateSelected];
    _priceSortedBtn.selected = YES;
    _priceSortedBtn.titleLabel.font = kUHSystemFontWithSize(14);
    _priceSortedBtn.frame = CGRectMake(0, 0, SW(3), _screeningBgView.height);
    [_priceSortedBtn addTarget:self action:@selector(priceClick:) forControlEvents:UIControlEventTouchUpInside];

    
    NSArray *arr = @[@"热销", @"热评"];
    for (int i = 0; i < arr.count; i++) {
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(SW(3)+SW(3)*i, 0, 1, _priceSortedBtn.height)];
        [_screeningBgView addSubview:line];
        line.backgroundColor = kLightGrayColor;
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_screeningBgView addSubview:btn];
        [btn setTitle:arr[i] forState:UIControlStateNormal];
        [btn setTitleColor:kBlackColor forState:UIControlStateNormal];
        [btn setTitleColor:kRedColor forState:UIControlStateSelected];
        btn.titleLabel.font = kUHSystemFontWithSize(14);
        btn.frame = CGRectMake(SW(3)+SW(3)*i, 0, SW(3), _priceSortedBtn.height);
        btn.tag = 1+i;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    // collectionView
    
    // 集合视图 collectionView所有布局的父类
    // 系统提供自带的布局类
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 默认为纵向滑动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.minimumLineSpacing = 10;
    
    // 创建collectionView
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 44, SCREEN_WIDTH, self.view.height-64-44) collectionViewLayout:flowLayout];
    [self.view addSubview:_collectionView];
    _collectionView.backgroundColor = UISeparatedColorRGB;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [_collectionView registerNib:[UINib nibWithNibName:@"MallsCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"item"];
    
    CGSize size1 = [LZCTools textSizeWithText:@"x" font:kUHSystemFontWithSize(12)];
    _collectionW = (SCREEN_WIDTH-30)/2;
    _collectionH = _collectionW+20+size1.height*3;
    
    _pickerBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:_pickerBgView];
    _pickerBgView.backgroundColor = RGBA(0, 0, 0, 0.2);
    _pickerBgView.hidden = YES;
    
    //初始化mainPickView
    _picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SH(3))];
    [self.view addSubview:_picker];
    _picker.delegate = self;
    _picker.dataSource = self;
    _picker.backgroundColor = UISeparatedColorRGB;
    _picker.showsSelectionIndicator = YES;
    

    _pickerToolbgView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 40)];
    [self.view addSubview:_pickerToolbgView];
    _pickerToolbgView.backgroundColor = UISeparatedColorRGB;
    
    NSArray *arr2 = @[@"取消", @"确定"];
    for (int i = 0; i < arr2.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_pickerToolbgView addSubview:btn];
        [btn setTitle:arr2[i] forState:UIControlStateNormal];
        [btn setTitleColor:kBlackColor forState:UIControlStateNormal];
        btn.titleLabel.font = kUHSystemFontWithSize(12);
        if (i==0) {
            btn.frame = CGRectMake(0, 0, 50, 40);
            [btn addTarget:self action:@selector(pickerRemove) forControlEvents:UIControlEventTouchUpInside];
        }
        else {
            btn.frame = CGRectMake(SCREEN_WIDTH-50, 0, 50, 40);
            [btn addTarget:self action:@selector(priceBtnText) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 39, SCREEN_WIDTH, 1)];
    [_pickerToolbgView addSubview:line];
    line.backgroundColor = kLightGrayColor;
    
}

#pragma mark ==========UICollectionView==========
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    _item = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    
    _item.model = self.infoArr[indexPath.row];
    
    return _item;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.infoArr.count;
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //    NSLog(@"%f", _item.cover.height);
    //    return CGSizeMake((SCREEN_WIDTH-30)/2, _item.money.y+_item.money.height+10);
    return CGSizeMake(_collectionW, _collectionH);
}
//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"点击collectionView.item = %ld", indexPath.row);
    
    Goods *model = self.infoArr[indexPath.row];
    
    MallDetailViewController *detailVC = [[MallDetailViewController alloc] init];
	detailVC.isBuytogetherMode = model.is_ecbuy;
    detailVC.goodId = model.goods_id;
    [self.navigationController pushViewController:detailVC animated:YES];
    
}
#pragma mark ==========UIPickerView==========
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView
{
    return 1; // 返回1表明该控件只包含1列
}
//UIPickerViewDataSource中定义的方法，该方法的返回值决定该控件指定列包含多少个列表项
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    // 由于该控件只包含一列，因此无须理会列序号参数component
    // 该方法返回books.count，表明books包含多少个元素，该控件就包含多少行
    return self.pickerArr.count;
}
// UIPickerViewDelegate中定义的方法，该方法返回的NSString将作为UIPickerView
// 中指定列和列表项的标题文本
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    // 由于该控件只包含一列，因此无须理会列序号参数component
    // 该方法根据row参数返回books中的元素，row参数代表列表项的编号，
    // 因此该方法表示第几个列表项，就使用books中的第几个元素
    return [self.pickerArr objectAtIndex:row];
}
// 当用户选中UIPickerViewDataSource中指定列和列表项时激发该方法
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//    [_priceSortedBtn setTitle:self.pickerArr[row] forState:UIControlStateNormal];
    self.pickerStr = self.pickerArr[row];
}

#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        weakSelf.page++;
        [weakSelf GETMallsGoods];
    }];
    
}

#pragma mark ===========响应方法==========
// 点击热销和热评
- (void)btnClick:(UIButton *)sender {
    
//    [sender setTitleColor:kRedColor forState:UIControlStateNormal];
    
//    if ([sender.titleLabel.text isEqualToString:@"热销"]) {
//        self.pickerStr = @"sold_num";
//    }
//    else
//        self.pickerStr = @"comments_count";
    
    if (sender.tag == 1) {
        self.pickerStr = @"sold_num";
        sender.selected = YES;
        UIButton *btn = [self.view viewWithTag:2];
        btn.selected = NO;
        _priceSortedBtn.selected = NO;
    }
    else {
        self.pickerStr = @"comments_count";
        sender.selected = YES;
        UIButton *btn = [self.view viewWithTag:1];
        btn.selected = NO;
        _priceSortedBtn.selected = NO;
    }
    
    
    self.page = 1;
    self.isTop = 1;
    
    [self GETMallsGoods];
}

- (void)GETMallsGoods {
    
    
    // GET /malls/goods 获取商品 keyword 关键词，匹配商品名 page 页码，默认为1 per_page 每页显示数，默认为10 orderby 排序字段 price（价格，默认），sold_num（销量），comments_count（评价数）direction 排序方式 desc（降序，默认）asc（升序）
    
    NSDictionary *param;
    NSString     *name;
    if (self.type == 1) {
        if (self.pickerStr.length == 0) {
            param = @{@"per_page":@"6", @"page":[NSString stringWithFormat:@"%ld", self.page], @"cate_id":self.cate_id};
        }
        else if ([self.pickerStr isEqualToString:@"价格↑"]) {
            param = @{@"per_page":@"6", @"page":[NSString stringWithFormat:@"%ld", self.page], @"cate_id":self.cate_id, @"orderby":@"price", @"direction":@"asc"};
        }
        else if ([self.pickerStr isEqualToString:@"价格↓"]) {
            param = @{@"per_page":@"6", @"page":[NSString stringWithFormat:@"%ld", self.page], @"cate_id":self.cate_id, @"orderby":@"price", @"direction":@"desc"};
        }
        else
            param = @{@"per_page":@"6", @"page":[NSString stringWithFormat:@"%ld", self.page], @"cate_id":self.cate_id, @"orderby":self.pickerStr, @"direction":@"desc"};
        name = @"获取商品分类";
    }
    else {
        if (self.pickerStr.length == 0) {
            param = @{@"per_page":@"6", @"page":[NSString stringWithFormat:@"%ld", self.page], @"keyword":self.titleName};
        }
        else if ([self.pickerStr isEqualToString:@"价格↑"]) {
            param = @{@"per_page":@"6", @"page":[NSString stringWithFormat:@"%ld", self.page], @"keyword":self.titleName, @"orderby":@"price", @"direction":@"asc"};
        }
        else if ([self.pickerStr isEqualToString:@"价格↓"]) {
            param = @{@"per_page":@"6", @"page":[NSString stringWithFormat:@"%ld", self.page], @"keyword":self.titleName, @"orderby":@"price", @"direction":@"desc"};
        }
        else
            param = @{@"per_page":@"6", @"page":[NSString stringWithFormat:@"%ld", self.page], @"keyword":self.titleName, @"orderby":self.pickerStr, @"direction":@"desc"};
        name = @"获取搜索商品";
    }
    
    
    [[NetworkTool sharedTool] requestWithName:name URLString:APIMallsGoods parameters:param method:@"GET" callBack:^(id responseObject) {
        
        NSArray *arr = responseObject[@"data"];
        
        if (self.page == 1) {
            [self.infoArr removeAllObjects];
        }
        if (arr.count == 0) {
            self.page--;
            if (self.page == 0) {
                self.page = 1;
            }
        }
        
        for (NSDictionary *dic in arr) {
            Goods *model = [[Goods alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.infoArr addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [_collectionView.mj_footer endRefreshing];
            [_collectionView reloadData];
            if (self.isTop) {
                [_collectionView setContentOffset:CGPointMake(0,0) animated:NO];
                self.isTop = 0;
            }
        });
        
    }];
}

- (void)navRithAction:(id)sender {
    NSLog(@"导航有按钮被点击");
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    searchVC.type = 3;
    [self.navigationController pushViewController:searchVC animated:YES];
}

- (void)priceClick:(UIButton *)sender {
    NSLog(@"点击综合，弹出选择器");
    sender.selected = YES;
    UIButton *btn1 = [self.view viewWithTag:1];
    UIButton *btn2 = [self.view viewWithTag:2];
    btn1.selected = NO;
    btn2.selected = NO;
    self.pickerStr = @"价格↑";
    [self pickerShow];
}


- (void)priceBtnText {
//    if (self.pickerStr.length == 0) {
//        self.pickerStr = @"价格↑";
//    }
    self.page = 1;
    self.isTop = 1;
    [_priceSortedBtn setTitle:self.pickerStr forState:UIControlStateNormal];
    [self.infoArr removeAllObjects];
    [self GETMallsGoods];
    [self pickerRemove];
//    [_collectionView setContentOffset:CGPointMake(0,0) animated:YES];
    
}

- (void)pickerShow {
    _pickerBgView.hidden = NO;
    [UIView animateWithDuration:0.33 animations:^{
        _pickerToolbgView.y = SH(3)*2-104;
        _picker.y = SH(3)*2-64;
    } completion:^(BOOL finished) {
    }];
    
}
- (void)pickerRemove {
    
    [UIView animateWithDuration:0.33 animations:^{
        _pickerToolbgView.y = SCREEN_HEIGHT;
        _picker.y = SCREEN_HEIGHT;
    } completion:^(BOOL finished) {
        _pickerBgView.hidden = YES;
    }];
}


- (void)returnAction:(UIButton *)sender {
    
    NSArray *array = self.navigationController.viewControllers;
    NSArray* reversedArray = [[array reverseObjectEnumerator] allObjects];
    for (UIViewController *controller in reversedArray) {
        if ([controller isKindOfClass:[MallHomeViewController class]]) {
             MallHomeViewController *vc =(MallHomeViewController *)controller;
            [self.navigationController popToViewController:vc animated:YES];
            return;
        }
//        else if ([controller isKindOfClass:[MallClassificationViewController class]]){
//            MallClassificationViewController *vc = (MallClassificationViewController *)controller;
//            [self.navigationController popToViewController:vc animated:YES];
//            return;
//        }
    }
}

// 懒加载
- (NSMutableArray *)infoArr {
    if (_infoArr == nil) {
        _infoArr = [[NSMutableArray alloc] init];
    }
    return _infoArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
